package com.chuangjiangx.member.manager.web.web.score.controller;

import com.chuangjiangx.commons.PageUtils;
import com.chuangjiangx.commons.page.PagingResult;
import com.chuangjiangx.commons.response.Response;
import com.chuangjiangx.commons.response.ResponseUtils;
import com.chuangjiangx.member.manager.basic.web.controller.BaseController;
import com.chuangjiangx.member.manager.basic.web.interceptor.Login;
import com.chuangjiangx.member.manager.basic.web.interceptor.Permissions;
import com.chuangjiangx.member.manager.common.Constants;
import com.chuangjiangx.member.manager.common.ThreadLocalUser;
import com.chuangjiangx.member.manager.web.web.basic.response.UploadFile;
import com.chuangjiangx.member.manager.web.web.score.request.CreateScoreGiftRequest;
import com.chuangjiangx.member.manager.web.web.score.request.ModifyScoreGiftRequest;
import com.chuangjiangx.member.manager.web.web.score.request.ModifyScoreGiftRuleInventoryRequest;
import com.chuangjiangx.member.manager.web.web.score.request.ScoreGiftForListRequest;
import com.chuangjiangx.member.manager.web.web.score.response.ScoreGiftDetailResponse;
import com.chuangjiangx.member.manager.web.web.score.response.ScoreGiftForListResponse;
import com.chuangjiangx.member.manager.web.web.stored.response.RuleNameResponse;
import com.chuangjiangx.member.score.ddd.application.MbrScoreGiftRuleApplication;
import com.chuangjiangx.member.score.ddd.application.command.CreateMbrScoreGiftRuleCommand;
import com.chuangjiangx.member.score.ddd.application.command.ModifyMbrScoreGiftRuleCommand;
import com.chuangjiangx.member.score.ddd.dal.condition.QueryScoreGiftRuleCondition;
import com.chuangjiangx.member.score.ddd.dal.dto.MbrScoreGiftRuleDetail;
import com.chuangjiangx.member.score.ddd.dal.dto.MemberScoreGiftRuleList;
import com.chuangjiangx.member.score.ddd.query.MbrScoreGiftRuleQuery;
import com.chuangjiangx.publicmodule.domain.upload.service.UploadFileService;
import com.sun.jmx.snmp.ThreadContext;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 积分兑换规则--商户权限
 */
@RestController
@RequestMapping(value = "/api/mbr/score-gift-rule", produces = "application/json")
public class MbrScoreGiftRuleController extends BaseController {

    @Autowired
    private MbrScoreGiftRuleApplication mbrScoreGiftRuleApplication;
    @Autowired
    private MbrScoreGiftRuleQuery mbrScoreGiftRuleQuery;
    @Autowired
    private UploadFileService uploadFileService;

    /**
     * 上传图片
     *
     * @param file 图片文件
     * @return 上传结果
     * @see UploadFile
     */
    @RequestMapping(value = "/uploadImage")
    @Login
    public Response uploadFile(MultipartFile file) throws Exception {
        UploadFile uploadFile = new UploadFile();
        String fileName = RandomStringUtils.randomAlphanumeric(8) + "." +FilenameUtils.getExtension(file.getOriginalFilename());
        String key = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + "/" + fileName;
        String filekey = uploadFileService.uploadFile(file.getInputStream(), key);
        uploadFile.setPic(key);
        if (filekey != null && !"".equals(filekey)) {
            //获取url
            uploadFile.setPreviewLink(uploadFileService.getDownloadUrl(filekey));
        }
        return ResponseUtils.success("uploadFile", uploadFile);
    }

    /**
     * 兑换规则列表
     *
     * @param session 获取用户信息session
     * @param param   请求参数
     * @return 列表
     * @map scoreGiftList List
     * @map page
     * @see ScoreGiftForListResponse
     * @see com.chuangjiangx.commons.page.Page
     */
    @RequestMapping(value = "/search-list")
    @Login
    @Permissions("50033")
    public Response searchScoreGiftList(
            HttpSession session,
            @Validated @RequestBody ScoreGiftForListRequest param) {

        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        QueryScoreGiftRuleCondition condition = new QueryScoreGiftRuleCondition();
        condition.setMerchantId(user.getMerchantId());
        condition.setGoodsName(param.getGoodsName());
        condition.setStatus(param.getStatus());
        PageUtils.copyPage(condition, param.getPage());
        PagingResult<MemberScoreGiftRuleList> result = mbrScoreGiftRuleQuery.findMbrScoreGiftRuleList(condition);
        result.getItems()
                .stream()
                .forEach(i -> {
                    /*
                     * 因在WEB提前结束操作后立马刷新列表，所以当前时间应放在循环内初始化，
                     * 且比较单位为毫秒。否则将出现已结束的状态显示为进行中。
                     */
                    final  Date now = new Date();
                    if(DateUtils.truncatedCompareTo(i.getStartTime(),now,Calendar.MILLISECOND) > 0){
                        //未开始
                        i.setStatus(0);
                    }else if(DateUtils.truncatedCompareTo(i.getEndTime(),now,Calendar.MILLISECOND) >= 0){
                        //进行中
                        i.setStatus(1);
                    }else{
                        //已结束
                        i.setStatus(2);
                    }
                });
        return ResponseUtils.successCamel(result);
    }

    /**
     * 新增兑换规则
     *
     * @param param   请求参数
     * @return 新增结果
     */
    @RequestMapping(value = "/create")
    @Login
    @Permissions("50030")
    public Response createScoreGift(
                                    @Validated @RequestBody CreateScoreGiftRequest param) throws Exception {

        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        CreateMbrScoreGiftRuleCommand command = new CreateMbrScoreGiftRuleCommand();
        BeanUtils.copyProperties(param,command);
        command.setMerchantId(user.getMerchantId());
        mbrScoreGiftRuleApplication.createMbrScoreGiftRule(command);
        return ResponseUtils.success();
    }

    /**
     * 修改兑换规则
     *
     * @param param   请求参数
     * @return 修改结果
     */
    @RequestMapping(value = "/update")
    @Login
    @Permissions("50031")
    public Response ScoreGift(
                              @Validated @RequestBody ModifyScoreGiftRequest param) throws Exception {
        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        ModifyMbrScoreGiftRuleCommand command = new ModifyMbrScoreGiftRuleCommand();
        BeanUtils.copyProperties(param,command);
        command.setMerchantId(user.getMerchantId());
        mbrScoreGiftRuleApplication.modifyMbrScoreGiftRule(command);
        return ResponseUtils.success();
    }

    /**
     * 删除兑换规则
     *
     * @param id   兑换规则id
     * @return 删除结果
     */
    @RequestMapping(value = "/delete/{id}")
    @Login
    @Permissions("50032")
    public Response delete(
                                    @PathVariable Long id) throws Exception {
        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        mbrScoreGiftRuleApplication.delMbrScoreGiftRule(id, user.getMerchantId());
        return ResponseUtils.success();
    }

    /**
     * 根据id查询兑换规则详情
     *
     * @return 规则详情
     * @map scoreGift
     * @see ScoreGiftDetailResponse
     */
    @RequestMapping(value = "/search-detail/{id}")
    @Login
    @Permissions("50034")
    public Response searchDetail(
                                        @PathVariable Long id) {

        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        MbrScoreGiftRuleDetail detail = mbrScoreGiftRuleQuery.findByIdAndMerchantId(id, user.getMerchantId());
        return ResponseUtils.successCamel(detail);
    }

    /**
     * 查询所有的规则
     *
     * @return 规则
     * @map rule
     * @see RuleNameResponse
     */
    @RequestMapping(value = "/all-rule-name")
    @Login
    @Permissions("50035")
    public Response queryAllRuleName() {
        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        List<String> list = mbrScoreGiftRuleQuery.findValidList(user.getMerchantId())
                .stream()
                .map(s -> s.getName())
                .collect(Collectors.toList());
        return ResponseUtils.successCamel(list);
    }

    /**
     * 结束活动(结束积分兑换规则)
     * @param session
     * @return
     */
    @RequestMapping(value = "/end/{id}")
    @Login
    @Permissions("50036")
    public Response end(
                        @PathVariable Long id) {
        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        mbrScoreGiftRuleApplication.finishActivity(id,user.getMerchantId());
        return ResponseUtils.successCamel();
    }


    /**
     * 修改积分兑换规则库存
     * @param session
     * @param request
     * @return
     */
    @RequestMapping(value = "/update-inventory",method = RequestMethod.POST)
    @Login
    @Permissions("50036")
    public Response end(
                        @RequestBody @Validated ModifyScoreGiftRuleInventoryRequest request) {
        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        MbrScoreGiftRuleDetail rule = mbrScoreGiftRuleQuery.findByIdAndMerchantId(request.getId(), user.getMerchantId());
        if(rule == null){
            return ResponseUtils.errorCamel("","规则不存在");
        }
        if(!Objects.equals(user.getMerchantId(),rule.getMerchantId())){
            return ResponseUtils.errorCamel("","您无权限操作");
        }
        mbrScoreGiftRuleApplication.updateInventory(request.getId(),request.getInventory().intValue());
        return ResponseUtils.successCamel();
    }
}